"""
简单的测试服务器 - 用于验证前端修复
"""
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from datetime import datetime
import uvicorn

app = FastAPI(title="订单测试服务器")

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class OrderCreateRequest(BaseModel):
    goods_ids: list[int]
    quantities: list[int]
    address_id: int = None
    remark: str = ""

@app.get("/")
async def root():
    return {"message": "订单测试服务器运行中"}

@app.get("/api/orders/test-connection")
async def test_connection():
    """测试连接"""
    return {
        "code": 200,
        "message": "连接测试成功",
        "data": {
            "host": "127.0.0.1",
            "port": 8000,
            "queue": "test_queue",
            "timestamp": datetime.now().isoformat()
        }
    }

@app.post("/api/orders/create")
async def create_order(order_request: OrderCreateRequest):
    """创建订单"""
    try:
        print(f"收到订单请求: {order_request}")
        
        # 验证数据
        if len(order_request.goods_ids) != len(order_request.quantities):
            return {
                "code": 400,
                "message": "商品ID和数量列表长度不匹配",
                "data": None
            }
        
        # 生成订单号
        timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
        import random
        random_num = random.randint(1000, 9999)
        order_no = f"XHS{timestamp}{random_num}"
        
        print(f"生成订单号: {order_no}")
        
        return {
            "code": 200,
            "message": "订单创建成功，正在处理中",
            "data": {
                "order_no": order_no,
                "status": "pending"
            }
        }
        
    except Exception as e:
        print(f"创建订单失败: {e}")
        return {
            "code": 500,
            "message": f"订单创建失败: {str(e)}",
            "data": None
        }

@app.get("/api/orders/status/{order_no}")
async def get_order_status(order_no: str):
    """查询订单状态"""
    return {
        "code": 200,
        "message": "查询成功",
        "data": {
            "order_no": order_no,
            "status": "processing",
            "message": "订单正在处理中...",
            "timestamp": datetime.now().isoformat()
        }
    }

if __name__ == "__main__":
    print("🚀 启动订单测试服务器...")
    print("📍 服务地址: http://127.0.0.1:8000")
    print("📖 API文档: http://127.0.0.1:8000/docs")
    print("🧪 测试页面: test_frontend_fix.html")
    
    uvicorn.run(
        app, 
        host="127.0.0.1", 
        port=8000, 
        log_level="info"
    )
